﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;
using Tdb.YY.DTO;

namespace Tdb.YY.DAL
{
    /// <summary>
    /// 数据层基类
    /// </summary>
    public class BaseDAL
    {
        #region 方法

        /// <summary>
        /// 查询列表
        /// </summary>
        /// <param name="q"></param>
        /// <param name="req">条件</param>
        /// <returns></returns>
        public async Task<PageList<T>> QueryPageList<T>(IQueryable<T> q, PageBaseReq req) where T : new()
        {
            //总条数
            var totalRecord = 0;

            //是否需要分页
            if (req.IsSetPage())
            {
                totalRecord = await q.CountAsync();
            }

            //设置排序和分页
            this.SetSortPage(ref q, req);

            //查询列表
            var list = await q.ToListAsync();

            //是否需要分页
            if (req.IsSetPage() == false)
            {
                totalRecord = list.Count;
            }

            return new PageList<T>(list, totalRecord);
        }

        /// <summary>
        /// 设置排序和分页
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="q"></param>
        /// <param name="req">条件</param>
        protected void SetSortPage<T>(ref IQueryable<T> q, PageBaseReq req)
        {
            //排序
            if (string.IsNullOrWhiteSpace(req.Sort) == false)
            {
                q = q.OrderBy(req.Sort);
            }

            //分页
            if (req.IsSetPage())
            {
                q = q.Skip(req.GetSkip()).Take(req.PageSize);
            }
        }

        #endregion
    }
}
